<?php

namespace app\mfw_order\controller;

use think\Db;

require_once EXTEND_PATH.'newMfw-sdk/Openapi.php';

class NewMfwOrder
{

    public $count = 1;
    /**
     * 构造函数
     * MfwComment constructor.
     */
    public function __construct(){}

    /**
     *  子进程启动时触发
     * @param $worker
     */
    public function onWorkerStart($worker){
        echo "马蜂窝订单子进程启动了\n";
        \workerman\Lib\Timer::add(100,[$this, 'timeTask1']);
//        if ($worker->id === 0){
//            // 生成日期和删除日期
//            sleep(10);
//            \workerman\Lib\Timer::add(30,[$this, 'dealDate']);
//        }elseif ($worker->id === 1){
//            sleep(10);
//            \workerman\Lib\Timer::add(100,[$this, 'timeTask']);
//        }elseif ($worker->id === 2){
//            sleep(10);
//            \workerman\Lib\Timer::add(100,[$this, 'timeTask1']);
//        }
    }

    /**
     *  定时任务,获取所有订单列表
     */
    public function timeTask()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select(12);
        $date = $redis->lPop('mfw_order_date');
        if (!empty($date)){
            $isDatePage = $redis->get($date); // 查看当前的订单日期是否超过20
            $pageNo = 1; // 页数
            if (!empty($isDatePage)){
                $pageData = explode('-', $isDatePage);
                if ($pageData[0] >= $pageData[1]){
                    $redis->rPush('mfw_order_date1', $date);
                    $redis->del($date);
                    return false;
                }else{
                    $pageNo = $pageNo + 1;
                }
            }
            $this->getMfwOrder($pageNo, $date,$date);
        }
    }

    /**
     *  定时任务1,获取订单详情
     */
    public function timeTask1()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select(12);
        $order_id = $redis->lPop('mfw_order_id_list');
        if (!empty($order_id)){
            $this->getMfwOrderDetail($order_id);
        }
    }

    public function dealDate()
    {
        // 获取日期
        $this->getDate();
        // 删除日期
        $date = date('H:i:s', time());
        if ($date >= '23:50:00'){
            $this->dealDate();
        }
    }

    public function getDate()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select(12);
        $mfw_order_date = $redis->lRange('mfw_order_date', 0, -1);
        $mfw_order_date1 = $redis->lRange('mfw_order_date1', 0, -1);
        $date = [];
        if (!empty($mfw_order_date1)){
            $date = array_unique(array_merge($mfw_order_date, $mfw_order_date1));
        }else{
            $date = array_unique($mfw_order_date);
        }
        // 根据当前时间获取
        $currentDate = date('Y-m-d', time());
        $getDates = $this->getDayDate($currentDate, 1650);
        if (!empty($getDates) && !empty($date)){
            foreach ($getDates as $index => $getDate1) {
                if (!in_array($getDate1, $date)){
                    $redis->rPush('mfw_order_date', $getDate1);
                }
            }
        }elseif(empty($date)){
            foreach ($getDates as $index => $getDate1) {
                $redis->rPush('mfw_order_date', $getDate1);
            }
        }
    }


    public function delDate()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select(12);
        $mfw_order_date1 = $redis->lRange('mfw_order_date1', 0, -1);
        // 根据当前时间获取
        $currentDate = date('Y-m-d', time());
        $getDates = $this->getDayDate($currentDate, 1650);
        if (!empty($getDates) && !empty($mfw_order_date1)){
            $count = count($mfw_order_date1);
            foreach ($mfw_order_date1 as $index => $item) {
                if (!in_array($item, $getDates)){
                    $redis->lRem('mfw_order_date1', $item, $count);
                }
            }
        }
    }

    /**
     *  获取前10天的日期
     */
    public function getDayDate($value = '', $day = 100)
    {
        $arr = [];
        $days = $day;
        $arr[] = $value;
        if (!empty($value)){
            for ($i = 1; $i < $days; $i++) {
                $arr[] = date('Y-m-d', strtotime("{$value} -{$i}day"));
            }
        }
        return $arr;
    }


    /**
     * 连接时触发
     * @param $connection
     */
    public function onConnect($connection){
        echo "连接成功\n";
        $connection->send('<h2 style="color: #4288ce;font-size: 20px">hello!</h2>');
    }

    /**
     *  接收到消息时触发
     * @param $connection
     * @param $message
     */
    public function onMessage($connection, $message) {
        var_dump($message);
        $connection->send("<span style='color: #000088;'>很高兴和你认识</span>\n");
    }

    /**
     *  连接关闭时触发
     * @param $connection
     */
    public function onClose($connection){
        echo "连接断开了\n";
    }

    /**
     *  worker进程停止时触发
     * @param $connection
     */
    public function onWorkerStop($connection){
        echo "正在重启!\n";
    }


    /**
     *  获取马蜂窝订单
     * @author 邓汉炜
     * @param $page_no 页码
     * @param $time_from 用户下单起始时间
     * @param $time_to 用户下单结束时间
     * @url /mfw_order/new_mfw_order/getMfwOrder
     */
    public function getMfwOrder($page_no = 1, $time_from = '', $time_to = '')
    {
        echo "定时任务\n";
        $action = 'sales.order.list.get'; // 调用接口
        $data = [];
        $data['page_no'] = empty($page_no)?1:$page_no; // 当前页数
        if (!empty($time_from)){
            $data['params']['time_from'] = $time_from;
        }
        if (!empty($time_to)){
            $data['params']['time_to'] = $time_to;
        }
        // 实例化请求
        $mfwObj = new \MSDK_Php_Openapi();
        // 创建redis对象
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select(12);
        // 请求接口
        if (false == $mfwObj->send($action, $data)){
            $msg['status'] = false;
            $msg['error_id'] = 19060511;
            $msg['msg'] = '接口调用失败';
            $msg['get_msg'] = $mfwObj->getError();
            $msg['get_error'] = $mfwObj->getErrno();
            logs('NewMfwOrderListError', $msg);
        }else{
            $total = $mfwObj->getData()['total'];
            // 保存分页
            if (!empty($total) && $total>20){
                $getDateVal = $redis->get($time_from); // 获取当前日期的值,不存在返回false
                $pageNo = ceil($total/20);
                if (!$getDateVal){
                    $pageNumVal =  "1-".$pageNo;
                    $redis->set($time_from,$pageNumVal); // 设置查询的页数为1
                    $redis->rPush('mfw_order_date', $time_from);
                }else{
                    $pageNumVal =  $page_no."-".$pageNo;
                    $redis->set($time_from,$pageNumVal);
                    $redis->rPush('mfw_order_date', $time_from);
                }
            }else{
                $redis->rPush('mfw_order_date1', $time_from);
            }
            $result = $mfwObj->getData()['list'];
            if (!empty($result)){
                // 保存马蜂窝订单
                self::saveMfwOrder($result);
            }
        }
    }


    /**
     *  把马蜂窝订单保存进数据表里面
     */
    public static function saveMfwOrder($data = [])
    {
        if (!empty($data) && count($data) > 1){
            foreach ($data as $index => $datum) {
                $redis = new \Redis();
                $redis->connect('127.0.0.1',6379);
                $redis->select(12);
                $redis->rPush('mfw_order_id_list', $datum['orderId']);
                $find = Db::name('mfw_booking_people')->where('mfw_order_id',$datum['orderId'])->find();
                if ($find){
                    continue;
                }
                $saveData = [];
                $people = [];
                if (!empty($datum['bookingPeople'])){
                    $people = [
                        'uid' => $datum['bookingPeople']['uid'],
                        'name' => $datum['bookingPeople']['name'],
                        'email' => $datum['bookingPeople']['email'],
                        'mfw_order_id' => $datum['orderId'],
                        'phone_area' => $datum['bookingPeople']['phone_area'],
                        'phone' => $datum['bookingPeople']['phone'],
                        'wechat' => $datum['bookingPeople']['wechat'],
                        'remark' => $datum['bookingPeople']['remark'],
                    ];
                }
                $mfw_booking_people_id = Db::name('mfw_booking_people')->strict(false)->insertGetId($people);
                $saveData['order_id'] = $datum['orderId'];
                $saveData['order_status'] = $datum['status']['orderStatus'];
                $saveData['refund_status'] = $datum['status']['refundStatus'];
                $saveData['all_refund_flag'] = $datum['status']['allRefundFlag'];
                $saveData['go_date'] = ($datum['goDate'] == '0000-00-00')?'':strtotime($datum['goDate']);
                $saveData['end_date'] = ($datum['endDate'] == '0000-00-00')?'':strtotime($datum['endDate']);
                $saveData['paytime'] = ($datum['paytime'] == '0000-00-00')?'':strtotime($datum['paytime']);
                $saveData['ctime'] = ($datum['ctime'] == '0000-00-00')?'':strtotime($datum['ctime']);
                $saveData['mfw_booking_people_id'] = $mfw_booking_people_id;
                $saveData['sales_id'] = $datum['salesId'];
                $saveData['sales_name'] = $datum['salesName'];
                $saveData['ota_sales_name'] = $datum['otaSalesName'];
                $saveData['sales_type'] = $datum['salesType'];
                $saveData['mdd'] = $datum['mdd'];
                $saveData['from'] = $datum['from'];
                $saveData['sku_id'] = $datum['skuId'];
                $saveData['ota_sku_id'] = $datum['otaSkuId'];
                $saveData['sku_name'] = $datum['skuName'];
                $saveData['total_price'] = $datum['totalPrice'];
                $saveData['payment_fee'] = $datum['paymentFee'];
                $saveData['create_time'] = time();
                $saveData['items'] = json_encode($datum['items'],JSON_UNESCAPED_UNICODE);
                $saveData['promotion_detail'] = json_encode($datum['promotionDetail'],JSON_UNESCAPED_UNICODE);
                $saveData['skus'] = json_encode($datum['skus'],JSON_UNESCAPED_UNICODE);
                $saveData['data'] = json_encode($datum,JSON_UNESCAPED_UNICODE);

                // 存进数据表
                $find = Db::name('mfw_order')->where('order_id', $saveData['order_id'])->find();
                if ($find){
                    Db::name('mfw_order')->where('order_id', $saveData['order_id'])->strict(false)->update($saveData);
                }else{
                    Db::name('mfw_order')->strict(false)->insert($saveData);
                }
                // 把马蜂窝的订单同步到订单表中
                $saveData['people'] = $datum['bookingPeople'];
                $saveData['reduce_ota'] = $datum['promotionDetail']['reduce_ota'];
                $saveData['reduce_mfw'] = $datum['promotionDetail']['reduce_mfw'];
                self::saveOrder($saveData);
            }
        }
    }



    /**
     *  同步订单
     */
    public static function saveOrder($data = [])
    {
        if (!empty($data)){
            $saveData = [];
            $saveData['order_id'] = $data['order_id'];
            // 订单状态：1-待支付，2-待出单，4-已出单，5-已完成，6-已关闭
            switch ($data['order_status']){
                case 1 : $saveData['order_status'] = 'pay_for'; break;
                case 2 : $saveData['order_status'] = 'pending'; break;
                case 4 : $saveData['order_status'] = 'issue'; break;
                case 5 : $saveData['order_status'] = 'finish'; break;
                case 6 : $saveData['order_status'] = 'close'; break;
                default : $saveData['order_status'] = 'pay_for';
            }
            if ($data['all_refund_flag']){
                $saveData['isrefund'] = 1; //1 未全部退款 2 已全部退款
            }else{
                $saveData['isrefund'] = 0;// 0 无退款
            }
            // 1-已完成退款 2-已申请退款 3-拒绝退款 4-已确认退款 0-可发起退款
            switch ($data['refund_status']) {
                case 1: $saveData['refund_status'] = 'refunded'; break;
                case 2: $saveData['refund_status'] = 'check'; break;
                case 3: $saveData['refund_status'] = 'rejected'; break;
                case 4: $saveData['refund_status'] = 'refunding'; break;
                default: $saveData['refund_status'] = '';
            }
            $saveData['money'] = $data['payment_fee'];
            $saveData['title'] = $data['sales_name'];
            $saveData['platform'] = 'mfw';
            $saveData['start_time'] =$data['go_date'];
            $saveData['end_time'] =$data['end_date'];
            $saveData['booking_people_name'] =$data['people']['name'];
            $saveData['booking_people_email'] =$data['people']['email'];
            $saveData['booking_people_phone'] =$data['people']['phone'];
            $saveData['booking_people_wechat'] =$data['people']['wechat'];
            $saveData['booking_people_remark'] =$data['people']['remark'];
            $saveData['booking_people_phone_area'] =$data['people']['phone_area'];
            $saveData['uid'] =$data['people']['uid'];
            $saveData['sales_id'] =$data['sales_id'];
            $saveData['ctime'] =$data['ctime'];
            $saveData['sku_id'] =$data['sku_id'];
            $saveData['sales_name'] =$data['sales_name'];
            $saveData['sku_name'] =$data['sku_name'];
            $saveData['total_price'] =$data['total_price'];
            $saveData['payment_fee'] =$data['payment_fee'];
            $saveData['reduce_ota'] =$data['reduce_ota'];
            $saveData['reduce_mfw'] =$data['reduce_mfw'];
            $saveData['ota_sales_name'] =$data['ota_sales_name'];
            $saveData['dispose_status'] ='no_contact';
            // 保存到订单表
            $find = Db::name('order')->where('order_id',$saveData['order_id'])->find();
            if ($find){
                Db::name('order')->where('order_id',$saveData['order_id'])->strict(false)->update($saveData);
            }else{
                Db::name('order')->strict(false)->insert($saveData);
            }
        }
    }


    /**
     *  获取马蜂窝订单详情
     * @author 邓汉炜
     * @url /mfw_order/new_mfw_order/getMfwOrderDetail
     */
    public function getMfwOrderDetail($order_id = '')
    {
        if (!empty($order_id)){
            $action = 'sales.order.detail.get'; // 调用接口
            $data = [];
            $data['order_id'] = $order_id;
            // 创建redis对象
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            $redis->select(12);// 实例化请求
            $mfwObj = new \MSDK_Php_Openapi();
            if (false == $mfwObj->send($action, $data)){
                $msg['status'] = false;
                $msg['error_id'] = 19060511;
                $msg['msg'] = '接口调用失败';
                $msg['get_msg'] = $mfwObj->getError();
                $msg['get_error'] = $mfwObj->getErrno();
                logs('NewMfwOrderListError', $msg);
            }else {
                $result = $mfwObj->getData();
                if (!empty($result)){
                    $find = Db::name('mfw_booking_people')->where('mfw_order_id',$result['orderId'])->find();
                    $saveData = [];
                    $people = [];
                    if (!empty($result['bookingPeople'])){
                        $people = [
                            'uid' => $result['bookingPeople']['uid'],
                            'name' => $result['bookingPeople']['name'],
                            'email' => $result['bookingPeople']['email'],
                            'mfw_order_id' => $result['orderId'],
                            'phone_area' => $result['bookingPeople']['phone_area'],
                            'phone' => $result['bookingPeople']['phone'],
                            'wechat' => $result['bookingPeople']['wechat'],
                            'remark' => $result['bookingPeople']['remark'],
                        ];
                    }

                    if ($find){
                        $mfw_booking_people_id =$find['id'];
                        Db::name('mfw_booking_people')->where('id', $mfw_booking_people_id)->strict(false)->update($people);
                    }else{
                        $mfw_booking_people_id = Db::name('mfw_booking_people')->strict(false)->insertGetId($people);
                    }
                    $saveData['order_id'] = $result['orderId'];
                    $saveData['order_status'] = $result['status']['orderStatus'];
                    $saveData['refund_status'] = $result['status']['refundStatus'];
                    $saveData['all_refund_flag'] = $result['status']['allRefundFlag'];
                    $saveData['go_date'] = ($result['goDate'] == '0000-00-00')?'':strtotime($result['goDate']);
                    $saveData['end_date'] = ($result['endDate'] == '0000-00-00')?'':strtotime($result['endDate']);
                    $saveData['paytime'] = ($result['paytime'] == '0000-00-00')?'':strtotime($result['paytime']);
                    $saveData['ctime'] = ($result['ctime'] == '0000-00-00')?'':strtotime($result['ctime']);
                    $saveData['mfw_booking_people_id'] = $mfw_booking_people_id;
                    $saveData['sales_id'] = $result['salesId'];
                    $saveData['sales_name'] = $result['salesName'];
                    $saveData['ota_sales_name'] = $result['otaSalesName'];
                    $saveData['sales_type'] = $result['salesType'];
                    $saveData['mdd'] = $result['mdd'];
                    $saveData['from'] = $result['from'];
                    $saveData['sku_id'] = $result['skuId'];
                    $saveData['ota_sku_id'] = $result['otaSkuId'];
                    $saveData['sku_name'] = $result['skuName'];
                    $saveData['total_price'] = $result['totalPrice'];
                    $saveData['payment_fee'] = $result['paymentFee'];
                    $saveData['create_time'] = time();
                    $saveData['items'] = json_encode($result['items'],JSON_UNESCAPED_UNICODE);
                    $saveData['promotion_detail'] = json_encode($result['promotionDetail'],JSON_UNESCAPED_UNICODE);
                    $saveData['skus'] = json_encode($result['skus'],JSON_UNESCAPED_UNICODE);
                    $saveData['data'] = json_encode($result,JSON_UNESCAPED_UNICODE);

                    // 存进数据表
                    $find = Db::name('mfw_order')->where('order_id',$saveData['order_id'])->find();
                    if ($find){
                        Db::name('mfw_order')->where('order_id',$saveData['order_id'])->strict(false)->update($saveData);
                    }else{
                        Db::name('mfw_order')->strict(false)->insert($saveData);
                    }
                    // 把马蜂窝的订单同步到订单表中
                    $saveData['people'] = $result['bookingPeople'];
                    $saveData['reduce_ota'] = $result['promotionDetail']['reduce_ota'];
                    $saveData['reduce_mfw'] = $result['promotionDetail']['reduce_mfw'];
                    self::saveOrder($saveData);
                }
            }
        }
    }

}
